package com.apes.scm.masterdata.frame.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.rop.converter.DateUtils;
import com.apes.framework.util.EventUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.util.BuildTreeUtil;
import com.apes.util.BuildTreeUtilOne;
import com.apes.util.TreeUtil;
import com.apes.util.TreeUtilOne;
import com.apes.scm.masterdata.frame.model.Branch;
import com.apes.scm.masterdata.frame.repository.BranchRepository;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("branchService")
public class BranchService extends DomainService{
    @Autowired
    private BranchRepository branchRepository;

    @Autowired
    PartyRoleRepository partyRoleRepository;

    public Branch save(SimpleRequest request) {
        Branch branch = request.getO(Branch.class);
        return branchRepository.saveAndFlush(branch);
    }

    /**
     * 功能：查询
     *
     * @param request
     */
    public Page<Branch> findAll(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        return branchRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size")));
    }

    /**
     * 下拉查询
     * @param request
     * @return
     * @throws Exception
     */
    public Page<Branch> find(SimpleRequest request) {
        return branchRepository.find(request.get("key"), PageRequest.of(request.get("page"), request.get("size")));
    }


    public Branch update(SimpleRequest request) {
        Branch branch = request.getO(Branch.class);
        branch = branchRepository.saveAndFlush(branch);
//        synBMXX(branch);
        return branch;
    }

    public String delete(SimpleRequest request) throws Exception  {
//        Dept dept = request.getO(Dept.class);
//        deptRepository.delete(dept);

        String id = request.get("id");
        long versions = (Long) request.get("version");

        Branch branch = branchRepository.findOne(id);
        if (branch == null) throw new RuntimeException("行政部门【" + id + "】在系统中不存在。");
        if (branch.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        branchRepository.delete(branch);

        return "删除成功";


    }

    public Branch findOne(String id) {
        return branchRepository.findOne(id);
    }


    /**
     * 获取行政部门 树形json数据
     * @return
     */
    public JSONArray getTreeJson(SimpleRequest request){

        // Sort sort = new Sort(Sort.Direction., "parents.id");
        List<Branch> branchList=  branchRepository.findAllByValidEqualsOrderByParentsDesc(true);
        List<TreeUtil<Branch>> treeUtils = new ArrayList<TreeUtil<Branch>>();
        for(Branch branch:branchList){
            TreeUtil<Branch> treeUtil=new TreeUtil<Branch>();
            treeUtil.setId(branch.getId());
            treeUtil.setLabel(branch.getName());
            treeUtil.setData(branch.getId());
            if(branch.getParents() != null ){
                treeUtil.setParent(branch.getParents().getId());
            }else{
                treeUtil.setParent("");
            }
            if(branch.getLevels() == 1 ){
                treeUtil.setExpandedIcon("anticon anticon-star");//打开
                treeUtil.setCollapsedIcon("anticon anticon-star-o");//关闭
            }else if(branch.getLevels() == 2){
                treeUtil.setExpandedIcon("anticon anticon-eye");//打开
                treeUtil.setCollapsedIcon("anticon anticon-eye-o");//关闭
            }else if(branch.getLevels() == 3){
                treeUtil.setIcon("anticon anticon-environment");
            }
            treeUtils.add(treeUtil);
        }
        TreeUtil<Branch> root = BuildTreeUtil.build(treeUtils);
        JSONArray treeList=new JSONArray();
        treeList.add(JSONObject.parseObject(root.toString()));
        return  treeList;
    }



    /**
     * 获取行政部门 树形json数据
     * @return
     */
    public JSONArray getTreeJsonNew(SimpleRequest request){
        List<Branch> branchList=  branchRepository.findAllByValidEqualsOrderByParentsDesc(true);

        List<TreeUtilOne<Branch>> treeUtils = new ArrayList<TreeUtilOne<Branch>>();
        for(Branch branch:branchList){
            TreeUtilOne<Branch> treeUtil=new TreeUtilOne<Branch>();
            treeUtil.setId(branch.getId());
            treeUtil.setName(branch.getName());
            treeUtil.setParents(branch.getParents());
            treeUtil.setLevels(branch.getLevels());
            treeUtil.setLastStage(branch.isLastStage());
            treeUtil.setOrigin(branch.getOrigin());
            treeUtil.setValid(branch.isValid());
            treeUtil.setBranchType(branch.getBranchType());
            treeUtil.setVersion(branch.getVersion());
            treeUtils.add(treeUtil);
        }
        List<TreeUtilOne<Branch>> root = BuildTreeUtilOne.build(treeUtils);
        //JSONArray treeList=new JSONArray();
        //treeList.add(JSONObject.parseArray(root.toString()));
        return  JSONObject.parseArray(root.toString());
    }


    /**
     * 根据登录人的查询权限 查询权限范围内的部门树
     * @param request
     */
    public Page<Branch> findByLocalPermit(SimpleRequest request){
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        String topic = "event:aut.post.findLocalPermitItems";
        List<PartyRole> roleList = new ArrayList<>();
        Map body = MapUtil.mapper("postId", request.getPostId(), "purpose", "pp_search", "type", "pt_company");
        List<String> orgIds = (List<String>) EventUtil.sendSynEvent(this, topic, body).stream().findFirst().get();
        if(orgIds.isEmpty()){
            roleList.addAll(partyRoleRepository.findAllCompany());
        }
        roleList.forEach(s -> {
            orgIds.add(s.getId());
        });
        List<Branch> branchList = branchRepository.findByLocalPermit(orgIds,request.get("key"));
        Pageable pageable = PageRequest.of(request.get("page"), request.get("size"), sort);
        PageImpl<Branch> pPage = new PageImpl<>(branchList, pageable, branchList.size());
        return pPage;
    }

    public void synBMXX(Branch branch){
        // 同步到旧框架 部门信息
        JSONObject synBMXX = new JSONObject();
        synBMXX.put("BMID",branch.getId());
        synBMXX.put("BMMC",branch.getName());
        synBMXX.put("TS01", DateUtils.format(Optional.ofNullable(branch.getLastUpdatedStamp()).orElse(new Date()), "yyyyMMdd.HHmmss.SSS"));
        synBMXX.put("LRR","admin");
        synBMXX.put("LRRQ_SJ", DateUtils.format(Optional.ofNullable(branch.getCreateDate()).orElse(new Date()),"yyyy-MM-dd HH:mm:ss"));
        String topic = "event:cm.branchEntry.synBMXX";
        Boolean flg = (Boolean) EventUtil.sendSynEvent(this, topic, synBMXX).stream().findFirst().get();
        if (!flg){
            throw new RuntimeException("同步部门信息到旧框架时报错!");
        }

        // 同步 门店扩展信息
        JSONObject synMDKZXX = new JSONObject();
        synMDKZXX.put("MDID",branch.getId());
        synMDKZXX.put("MDMC",branch.getName());
        synMDKZXX.put("KYRQ_SJ",DateUtils.format(branch.getOpenDay(),"yyyy-MM-dd HH:mm:ss"));
        synMDKZXX.put("TS01", DateUtils.format(Optional.ofNullable(branch.getLastUpdatedStamp()).orElse(new Date()), "yyyyMMdd.HHmmss.SSS"));
        synMDKZXX.put("LRR","admin");
        synMDKZXX.put("LRRQ_SJ",DateUtils.format(Optional.ofNullable(branch.getCreateDate()).orElse(new Date()),"yyyy-MM-dd HH:mm:ss"));
        synMDKZXX.put("KYRQ",DateUtils.format(branch.getOpenDay(),"yyyy-MM-dd HH:mm:ss"));
        String MDKZXXtopic = "event:cm.branchEntry.synMDKZXX";
        Boolean MDKZXXflg = (Boolean) EventUtil.sendSynEvent(this, MDKZXXtopic, synMDKZXX).stream().findFirst().get();
        if (!MDKZXXflg){
            throw new RuntimeException("同步门店扩展信息到旧框架时报错!");
        }


    }


}
